package com.parkinginfo.adapters;

import java.util.ArrayList;

import com.parkinginfo.dbhelper.Place;
import com.parkinginfo.listviews.PlacesListItem;
import com.parkinginfo.manager.R;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;


public class PlacesListAdapter extends BaseAdapter {
	
	private int[] colors = new int[] { 0x30ffffff, 0x30808080 };
	
	private ArrayList<Place> places;
	private Context context;

	public PlacesListAdapter(Context context, ArrayList<Place> tasks) {
		System.out.println("Adapter created!");
		this.places = tasks;
		this.context = context;
	}

	public int getCount() {
		return places.size();
	}

	public Place getItem(int position) {
		return (null == places) ? null : places.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		PlacesListItem tli;
		System.out.println("Get View Called!");
		
		if (null == convertView) {
			tli = (PlacesListItem)View.inflate(context, R.layout.places_list_item, null);
		} else {
			tli = (PlacesListItem)convertView;
		}
		int colorPos = position % colors.length;
		tli.setBackgroundColor(colors[colorPos]);
		
		Place placem = places.get(position);
		System.out.println("position: "+position);
		System.out.println("location: "+placem.getLocation());
		tli.setPlace(places.get(position));
		return tli;
	}

	public void forceReload() {
		notifyDataSetChanged();
	}

	public void toggleTaskCompleteAtPosition(int position) {
		Place task = getItem(position);
		task.toggleComplete();
		notifyDataSetChanged();
	}

	public Long[] removeCompletedTasks() {
		ArrayList<Place> completedTasks = new ArrayList<Place>();
		ArrayList<Long> completedIds = new ArrayList<Long>();
		for (Place thePlace : places) {
			if (thePlace.isComplete()) {
				completedIds.add(thePlace.getId());
				completedTasks.add(thePlace);
			}
		}
		places.removeAll(completedTasks);
		notifyDataSetChanged();
		return completedIds.toArray(new Long[]{});
	}

}
